<template>
    <el-dialog v-model="state.show" :title="state.title" width="600px" destroy-on-close @closed="onClosed">
        <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item label="绑定店铺" prop="erpShopId">
                <el-select v-model="form.erpShopId" placeholder="请选择店铺" filterable @change="onSelectChange">
                    <el-option
                        v-for="item in state.erpShopList"
                        :key="item.erpShopId"
                        :label="item.erpShopName"
                        :value="item.erpShopId" />
                </el-select>
                <el-link type="primary" :underline="false" @click="getErpShopList">刷新</el-link>
                <el-link type="primary" :underline="false" @click="topErp">添加店铺</el-link>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="onConfirm(formRef)"> 确定 </el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import request from '@/request';
import { ElMessage } from 'element-plus';
import { reactive, ref, inject } from 'vue';

const bus = inject('bus');
const state = reactive({
    show: false,
    title: '绑定店铺',
    erpShopList: []
});

const formRef = ref(null);
const form = reactive({
    erpShopId: ''
});
const rules = {
    erpShopId: [{ required: true, message: '请选择店铺', trigger: 'change' }]
};
const onSelectChange = v => {
    Object.assign(
        form,
        state.erpShopList.find(item => item.erpShopId === v)
    );
};
const onClosed = () => {
    form.erpShopId = '';
};

const onConfirm = async formEl => {
    if (!formEl) return;
    await formEl.validate();
    await request('erpBindShop', form);
    ElMessage.success('绑定成功');
    bus.emit('tabSwitch');
};
/* 获取店铺列表 */
const getErpShopList = async () => {
    state.loading = true;
    const { data } = await request('erpShopList');
    state.erpShopList = Array.isArray(data.list) ? data.list : [];
    state.loading = false;
};

const topErp = () => {
    window.open('https://www.erp321.com/login.aspx');
};

const onOpen = query => {
    getErpShopList();
    state.show = true;
};
defineExpose({
    onOpen
});
</script>
<style lang="scss" scoped>
:deep(.el-form-item__error) {
    margin-top: 4px;
}
:deep(.el-form-item__content) {
    flex-wrap: nowrap;
    .el-link {
        min-width: max-content;
        margin-left: 14px;
    }
}
</style>
